<template>
  <div class="dashboard-container">
    <!-- 左侧菜单栏 -->
    <div class="sidebar">
      <!-- 企业Logo和标题 -->
      <div class="company-header">
        <div class="company-logo-container">
          <div class="company-logo">
            <img v-if="companyInfo.logo" :src="companyInfo.logo" alt="企业Logo" />
            <div v-else class="default-logo">{{ companyInfo.shortName?.charAt(0) || '智' }}</div>
          </div>
          <img 
            v-if="showVipBadge" 
            :src="vipIcon" 
            alt="VIP" 
            class="vip-badge"
          />
        </div>
        <h1 class="company-title">智聘系统企业后台管理系统</h1>
      </div>
      
      <!-- 菜单列表 -->
      <nav class="menu-nav">
        <div 
          v-for="menu in menuList" 
          :key="menu.name"
          class="menu-item-container"
        >
          <!-- 有子菜单的情况 -->
          <div 
            v-if="menu.children"
            class="menu-item has-children"
            :class="{ active: isMenuActive(menu) }"
            @click="toggleSubmenu(menu)"
          >
            <el-icon class="menu-icon">
              <component :is="menu.icon" />
            </el-icon>
            <span>{{ menu.name }}</span>
            <el-icon class="submenu-arrow" :class="{ 'is-open': openSubmenus.includes(menu.name) }">
              <ArrowDown />
            </el-icon>
          </div>
          
          <!-- 没有子菜单的情况 -->
          <router-link 
            v-else
            :to="menu.path"
            class="menu-item"
            :class="{ active: isMenuActive(menu.path) }"
          >
            <el-icon class="menu-icon">
              <component :is="menu.icon" />
            </el-icon>
            <span>{{ menu.name }}</span>
          </router-link>
          
          <!-- 子菜单 -->
          <div 
            v-show="openSubmenus.includes(menu.name)"
            class="submenu"
          >
            <router-link 
              v-for="submenu in menu.children"
              :key="submenu.path"
              :to="submenu.path"
              class="submenu-item"
              :class="{ active: isMenuActive(submenu.path) }"
            >
              <el-icon class="submenu-icon">
                <component :is="submenu.icon" />
              </el-icon>
              <span>{{ submenu.name }}</span>
            </router-link>
          </div>
        </div>
      </nav>
    </div>
    
    <!-- 右侧内容区域 -->
    <div class="main-content">
      <!-- 顶部Header -->
      <header class="top-header">
        <div class="breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item>首页</el-breadcrumb-item>
            <el-breadcrumb-item>{{ currentPageTitle }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="user-info">
          <!-- 主题切换开关 -->
          <div class="theme-switch">
            <el-switch
              :model-value="themeStore.isDark"
              @change="themeStore.toggleTheme"
              active-text="黑夜"
              inactive-text="白天"
              :active-icon="Moon"
              :inactive-icon="Sunny"
              inline-prompt
              size="large"
            />
          </div>
          
          <!-- HR申请授权按钮 -->
          <el-button 
            type="primary" 
            size="small"
            @click="openHrAuthDialog"
            class="hr-auth-btn"
          >
            HR申请授权
          </el-button>
          
          <span class="user-name">{{ userInfo.nickName }}</span>
          <el-avatar 
            :size="32" 
            :src="userInfo.face" 
            class="user-avatar"
          />
        </div>
      </header>
      
      <!-- 内容区域 -->
      <main class="content-area">
        <router-view />
      </main>
    </div>
    
    <!-- HR申请授权弹窗 -->
    <el-dialog
      v-model="showHrAuthDialog"
      title="HR申请授权"
      width="600px"
      :close-on-click-modal="false"
      class="hr-auth-dialog"
    >
      <div class="auth-content">
        <!-- 两列布局：左侧说明，右侧操作 -->
        <div class="auth-layout">
          <!-- 左侧说明区域 -->
          <div class="auth-left">
            <div class="auth-notice">
              <h4>申请流程说明：</h4>
              <p>成为企业HR需要在 <strong>APP端</strong> 进行以下操作：</p>
              <ol>
                <li>进入 <strong>我要招人</strong></li>
                <li>输入企业信息</li>
                <li>输入授权码</li>
              </ol>
            </div>
            
            <div class="auth-code-info">
              <h4>授权码说明：</h4>
              <ul>
                <li><el-icon><Warning /></el-icon> <strong>只能使用一次</strong></li>
                <li><el-icon><Clock /></el-icon> <strong>有效期3天</strong></li>
                <li><el-icon><View /></el-icon> <strong>只会显示一次</strong></li>
                <li><el-icon><Lock /></el-icon> <strong>请自行保存，切勿泄露</strong></li>
              </ul>
            </div>
          </div>
          
          <!-- 右侧操作区域 -->
          <div class="auth-right">
            <!-- 生成授权码区域 -->
            <div class="generate-section">
              <el-button 
                type="primary" 
                size="large"
                @click="generateAuthCode"
                :loading="generating"
                :disabled="!!authCode"
                class="generate-btn"
              >
                {{ authCode ? '授权码已生成' : '生成授权码' }}
              </el-button>
              
              <!-- 授权码显示区域 -->
              <div v-if="authCode" class="auth-code-display">
                <h4>您的授权码：</h4>
                <div class="code-container">
                  <span class="auth-code">{{ authCode }}</span>
                  <el-button 
                    type="success" 
                    size="small"
                    @click="copyAuthCode"
                    class="copy-btn"
                  >
                    <el-icon><CopyDocument /></el-icon>
                    复制
                  </el-button>
                </div>
                <p class="code-tip">请及时保存，授权码不会再次显示！</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeHrAuthDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { getUserInfoApi, getCompanyInfoApi, generateHrAuthCodeApi } from '../api/user'
import { useThemeStore } from '../stores/modules/theme'
import { Moon, Sunny, Warning, Clock, View, Lock, CopyDocument, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import vipIcon from '@/assets/images/home/VIP.png'

const route = useRoute()
const userInfo = ref({})
const companyInfo = ref({})
const themeStore = useThemeStore()

// HR授权相关状态
const showHrAuthDialog = ref(false)
const authCode = ref('')
const generating = ref(false)

// 菜单配置
const menuList = [
  { name: '控制面板', path: '/dashboard', icon: 'Monitor' },
  { name: '企业信息', path: '/dashboard/company', icon: 'OfficeBuilding' },
  { name: '订单管理', path: '/dashboard/orders', icon: 'Document' },
  { 
    name: '招聘管理', 
    icon: 'User',
    children: [
      { name: '招聘人员', path: '/dashboard/recruitment/hr-list', icon: 'UserFilled' },
      { name: '历史职位', path: '/dashboard/recruitment/job-history', icon: 'Document' },
      { name: '面试记录', path: '/dashboard/recruitment/interview-records', icon: 'ChatDotRound' }
    ]
  }
]

// 当前页面标题
const currentPageTitle = computed(() => {
  // 先检查是否有子菜单被激活
  for (const menu of menuList) {
    if (menu.children) {
      const activeSubmenu = menu.children.find(submenu => route.path === submenu.path)
      if (activeSubmenu) {
        return `${menu.name} - ${activeSubmenu.name}`
      }
    }
  }
  
  // 检查主菜单
  const currentMenu = menuList.find(menu => {
    if (menu.path) {
      return route.path === menu.path
    }
    return false
  })
  
  return currentMenu ? currentMenu.name : '首页'
})

// 判断是否显示VIP角标
const showVipBadge = computed(() => {
  if (!companyInfo.value.isVip || companyInfo.value.isVip !== 1) {
    return false
  }
  
  if (!companyInfo.value.vipExpireDate) {
    return false
  }
  
  // 检查VIP是否过期
  const currentDate = new Date()
  const expireDate = new Date(companyInfo.value.vipExpireDate)
  
  return expireDate > currentDate
})

// 判断菜单是否激活
const isMenuActive = (menu) => {
  // 如果是子菜单项，直接判断路径
  if (typeof menu === 'string') {
    return route.path === menu
  }
  
  // 如果是父菜单，检查是否有子菜单被激活
  if (menu.children) {
    return menu.children.some(submenu => route.path === submenu.path)
  }
  
  return false
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const data = await getUserInfoApi()
    userInfo.value = data
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 获取企业信息
const fetchCompanyInfo = async () => {
  try {
    const data = await getCompanyInfoApi()
    console.log("company info :",data);
    
    companyInfo.value = data
  } catch (error) {
    console.error('获取企业信息失败:', error)
  }
}

// 测试主题切换
const testThemeToggle = () => {
  console.log('测试按钮点击，当前主题状态:', themeStore.isDark)
  themeStore.toggleTheme()
  console.log('测试按钮点击后，主题状态:', themeStore.isDark)
}

// HR授权相关函数
const generateAuthCode = async () => {
  try {
    generating.value = true
    const response = await generateHrAuthCodeApi()
    
    authCode.value = response
    ElMessage.success('授权码生成成功！')
    
    // 自动滚动到授权码显示区域
    setTimeout(() => {
      const codeDisplay = document.querySelector('.auth-code-display')
      if (codeDisplay) {
        codeDisplay.scrollIntoView({ 
          behavior: 'smooth', 
          block: 'center' 
        })
      }
    }, 100)
  } catch (error) {
    console.error('生成授权码失败:', error)
    ElMessage.error(error.message || '生成授权码失败，请重试')
  } finally {
    generating.value = false
  }
}

const copyAuthCode = async () => {
  try {
    await navigator.clipboard.writeText(authCode.value)
    ElMessage.success('授权码已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请手动复制')
  }
}

const closeHrAuthDialog = () => {
  showHrAuthDialog.value = false
  // 关闭弹窗时清空授权码，确保安全
  authCode.value = ''
}

const openHrAuthDialog = () => {
  showHrAuthDialog.value = true
  // 打开弹窗时清空授权码
  authCode.value = ''
}

// 子菜单展开/收起状态
const openSubmenus = ref([])

const toggleSubmenu = (menu) => {
  const index = openSubmenus.value.indexOf(menu.name)
  if (index > -1) {
    openSubmenus.value.splice(index, 1)
  } else {
    openSubmenus.value.push(menu.name)
  }
}

onMounted(async () => {
  // 初始化主题
  console.log('Dashboard组件挂载，初始化主题')
  themeStore.initTheme()
  console.log('主题初始化完成，当前状态:', themeStore.isDark)
  
  // 获取用户和企业信息
  await Promise.all([fetchUserInfo(), fetchCompanyInfo()])
})
</script>

<style scoped>
.dashboard-container {
  display: flex;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
}

.sidebar {
  width: 280px;
  min-width: 280px;
  max-width: 280px;
  background: #2b394f !important;
  color: var(--text-primary);
  display: flex;
  flex-direction: column;
  box-shadow: var(--shadow);
  flex-shrink: 0;
}

.company-header {
  padding: 2rem 1.5rem;
  text-align: center;
  border-bottom: 1px solid var(--border-color);
}

.company-logo-container {
  position: relative;
  display: inline-block;
  margin-bottom: 1rem;
}

.company-logo {
  margin: 0;
}

.company-logo img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}

.default-logo {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: 500;
  margin: 0 auto;
}

.company-title {
  font-size: 0.95rem;
  font-weight: 400;
  margin: 0;
  line-height: 1.4;
  color: rgba(255, 255, 255, 0.9);
}

.menu-nav {
  flex: 1;
  padding: 2rem 0;
  width: 100%;
  overflow: hidden;
}

.menu-item-container {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 0.9rem 1.5rem;
  color: rgba(255, 255, 255, 0.85);
  text-decoration: none;
  transition: all 0.2s ease;
  border-left: 3px solid transparent;
  cursor: pointer;
  width: 100%;
  box-sizing: border-box;
  font-weight: 400;
}

.menu-item:hover {
  background: rgba(255, 255, 255, 0.08);
  color: white;
}

.menu-item.active {
  background: rgba(255, 255, 255, 0.1);
  color: white;
  border-left-color: #ffffff;
}

.menu-item.has-children {
  padding-right: 0.5rem; /* Adjust padding for arrow */
}

.menu-icon {
  margin-right: 0.8rem;
  font-size: 1.1rem;
  width: 20px;
  text-align: center;
}

.submenu-arrow {
  margin-left: auto; /* Push arrow to the right */
  font-size: 0.8rem;
  transition: transform 0.3s ease;
}

.submenu-arrow.is-open {
  transform: rotate(180deg);
}

.submenu {
  position: relative;
  width: 100%;
  background: rgba(0, 0, 0, 0.15);
  border-top: 1px solid rgba(255, 255, 255, 0.08);
  flex-direction: column;
  padding: 0;
  margin-top: 0;
  overflow: hidden;
  transform-origin: top;
  transition: all 0.2s ease;
}

.submenu-item {
  display: flex;
  align-items: center;
  padding: 0.75rem 1.5rem 0.75rem 3rem;
  color: rgba(255, 255, 255, 0.8);
  text-decoration: none;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
  font-size: 0.9rem;
  width: 100%;
  box-sizing: border-box;
}

.submenu-item:hover {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.submenu-item.active {
  background: rgba(255, 255, 255, 0.15);
  color: white;
  border-left-color: #fff;
}

.submenu-icon {
  margin-right: 0.8rem;
  font-size: 0.9rem;
  width: 16px;
  text-align: center;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--primary-bg);
  min-width: 0;
  overflow: hidden;
}

.top-header {
  height: 60px;
  background: var(--card-bg);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 2rem;
  box-shadow: var(--shadow);
  border-bottom: 1px solid var(--border-color);
}

.breadcrumb {
  font-size: 0.9rem;
  color: var(--text-primary);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 1.5rem;
}

.theme-switch {
  display: flex;
  align-items: center;
}

.user-name {
  font-size: 0.9rem;
  color: var(--text-primary);
}

.user-avatar {
  cursor: pointer;
}

.vip-badge {
  position: absolute;
  bottom: -2px;
  right: -2px;
  width: 24px;
  height: 24px;
  object-fit: contain;
  z-index: 10;
  border-radius: 50%;
  background: white;
  padding: 2px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

.content-area {
  flex: 1;
  overflow-y: auto;
}

/* 黑夜主题下的菜单样式调整 */
:deep(.el-switch__label) {
  color: var(--text-primary);
}

:deep(.el-switch__core) {
  border-color: var(--border-color);
}

/* 确保黑夜模式下侧边栏颜色正确 */
[data-theme="dark"] .sidebar {
  background: #1a202c !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
  }
  
  .user-info {
    gap: 1rem;
  }
  
  .theme-switch {
    margin-right: 0.5rem;
  }
}

/* HR申请授权相关样式 */
.hr-auth-btn {
  margin: 0 1rem;
}

.hr-auth-dialog /deep/ .el-dialog__body {
  padding: 1.5rem;
}

.auth-content {
  max-height: 70vh;
  overflow-y: auto;
}

.auth-layout {
  display: flex;
  gap: 2rem;
}

.auth-left, .auth-right {
  flex: 1;
}

.auth-notice {
  margin-bottom: 1.5rem;
}

.auth-notice h4 {
  color: var(--text-primary);
  margin-bottom: 0.75rem;
  font-size: 0.95rem;
}

.auth-notice p {
  color: var(--text-secondary);
  margin-bottom: 0.75rem;
  line-height: 1.5;
  font-size: 0.9rem;
}

.auth-notice ol {
  margin: 0.75rem 0;
  padding-left: 1.25rem;
}

.auth-notice li {
  color: var(--text-secondary);
  margin-bottom: 0.4rem;
  line-height: 1.4;
  font-size: 0.85rem;
}

.auth-notice strong {
  color: var(--text-primary);
}

.auth-code-info {
  background: var(--hover-bg);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  padding: 0.75rem;
  margin-top: 0.75rem;
}

.auth-code-info h4 {
  color: var(--text-primary);
  margin-bottom: 0.6rem;
  font-size: 0.85rem;
}

.auth-code-info ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.auth-code-info li {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  color: var(--text-secondary);
  margin-bottom: 0.4rem;
  font-size: 0.8rem;
}

.auth-code-info .el-icon {
  color: var(--el-color-warning);
  font-size: 0.9rem;
}

.generate-section {
  text-align: center;
  padding: 0.5rem 0;
}

.generate-btn {
  margin-bottom: 1rem;
}

.auth-code-display {
  background: var(--hover-bg);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  padding: 1rem;
  margin-top: 0.75rem;
}

.auth-code-display h4 {
  color: var(--text-primary);
  margin-bottom: 0.75rem;
  font-size: 0.9rem;
  text-align: center;
}

.code-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
  margin-bottom: 0.75rem;
}

.auth-code {
  background: var(--card-bg);
  border: 2px solid var(--el-color-success);
  border-radius: 4px;
  padding: 0.6rem 0.8rem;
  font-family: 'Courier New', monospace;
  font-size: 1rem;
  font-weight: bold;
  color: var(--el-color-success);
  letter-spacing: 1px;
  user-select: all;
}

.copy-btn {
  flex-shrink: 0;
}

.code-tip {
  color: var(--el-color-warning);
  font-size: 0.8rem;
  text-align: center;
  margin: 0;
  font-weight: 500;
}

.dialog-footer {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .auth-layout {
    flex-direction: column;
    gap: 1rem;
  }
  
  .auth-content {
    max-height: 60vh;
  }
}
</style>
